const { Sequelize, DataTypes } = require('sequelize');

// 创建数据库连接
const sequelize = new Sequelize({
  dialect: 'mysql',
  host: 'localhost',
  username: 'root',
  password: '12345678',
  database: 'gitlab_analysis',
  logging: false // 设置为true可以查看SQL日志
});

// 定义模型
// 项目配置模型
const ProjectConfig = sequelize.define('ProjectConfig', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  gitlabUrl: {
    type: DataTypes.STRING,
    allowNull: false
  },
  projectName: {
    type: DataTypes.STRING,
    allowNull: false
  },
  accessToken: {
    type: DataTypes.STRING,
    allowNull: false
  },
  description: {
    type: DataTypes.TEXT
  },
  // 添加链接状态字段
  connectionStatus: {
    type: DataTypes.ENUM('untested', 'connected', 'disconnected'),
    defaultValue: 'untested'
  },
  lastTestedAt: {
    type: DataTypes.DATE,
    allowNull: true
  }
});

// 分析报告模型
const AnalysisReport = sequelize.define('AnalysisReport', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  projectId: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
  projectName: {
    type: DataTypes.STRING,
    allowNull: false
  },
  startDate: {
    type: DataTypes.DATEONLY,
    allowNull: false
  },
  endDate: {
    type: DataTypes.DATEONLY,
    allowNull: false
  },
  totalCommits: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  features: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  bugfixes: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  refactorings: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  docs: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  others: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  testCoverage: {
    type: DataTypes.FLOAT,
    defaultValue: 0
  },
  aiSummary: {
    type: DataTypes.TEXT
  },
  keyAchievements: {
    type: DataTypes.JSON
  },
  criticalBugfixes: {
    type: DataTypes.JSON
  },
  codeQuality: {
    type: DataTypes.JSON
  },
  dailyCommits: {
    type: DataTypes.JSON
  },
  commitTypes: {
    type: DataTypes.JSON
  },
  reportData: {
    type: DataTypes.JSON
  },
  rawCommitLog: {
    type: DataTypes.JSON, // 使用JSON类型存储原始日志
    allowNull: true
  },
  status: {
    type: DataTypes.ENUM('generating', 'completed', 'failed'),
    defaultValue: 'generating'
  },
  generatedAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
});

// 测试数据库连接
async function testConnection() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    // 同步模型到数据库
    await sequelize.sync({ alter: true });
    console.log('所有模型已同步');
  } catch (error) {
    console.error('数据库连接失败:', error);
  }
}

module.exports = {
  sequelize,
  ProjectConfig,
  AnalysisReport,
  testConnection
};